use std::ops::{Range, RangeInclusive};

pub fn retire_time(time: &str, tp: &str) -> String {
    let (year, month) = time.split_once('-').unwrap();
    let year = year.parse::<u16>().unwrap();
    let month = month.parse::<u8>().unwrap();
    let policy = match tp {
        "男职工" => RetirementPolicy::new(1965..1977, 60..=63, 0.25),
        "原法定退休年龄55周岁女职工" => RetirementPolicy::new(1970..1982, 55..=58, 0.25),
        "原法定退休年龄50周岁女职工" => RetirementPolicy::new(1975..1985, 50..=55, 0.5),
        _ => return "".to_string(),
    };
    let delayed_months = policy.delayed_months(year, month);
    let retire_age: f64 = *policy.retire_age_range.start() as f64 + delayed_months as f64 / 12.0;
    let mut retire_year = year + *policy.retire_age_range.start() as u16 + delayed_months as u16 / 12;
    let mut retire_month = month + (delayed_months % 12) as u8;
    if retire_month > 12 {
        retire_month -= 12;
        retire_year += 1;
    }
    let retire_age = format!("{:.2}", retire_age);
    let retire_age = retire_age.trim_end_matches(".00");
    format!("{}-{:02},{},{:.0}", retire_year, retire_month, retire_age, delayed_months)
}

struct RetirementPolicy {
    year_range: Range<u16>,
    retire_age_range: RangeInclusive<u8>,
    retire_rate: f64,
}

impl RetirementPolicy {
    fn new(year_range: Range<u16>, retire_age_range: RangeInclusive<u8>, retire_rate: f64) -> Self {
        Self {
            year_range,
            retire_age_range,
            retire_rate,
        }
    }
    fn max_delayed_months(&self) -> u8 {
        (self.retire_age_range.end() - self.retire_age_range.start()) * 12
    }
    fn delayed_months(&self, year: u16, month: u8) -> u8 {
        if year < self.year_range.start {
            return 0;
        } else if year >= self.year_range.end {
            return self.max_delayed_months();
        }
        let exceed_years = (year - self.year_range.start) as u8;
        let exceed_months = exceed_years * 12 + month;
        (exceed_months as f64 * self.retire_rate).ceil() as u8
    }
}